import { pageRecord, saveVerify, updateRecord } from '@/services/api/api-assess-week-collect-app-record';
import { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-components';
import { Alert, message, Tag } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddRecord from './AddAppRecord';
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';
const weekStart = 1; // 1表示周一是一周的开始，0表示周日是一周的开始

interface TabAppRecordProps {}

const TabAppRecord: React.FC<TabAppRecordProps> = ({}) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const [saveVerifyData, setSaveVerifyDataState] =
    useState<AssessWeekCollectAppRecordData.SaveVerify>();

  /**
   * 获取 详情
   * @param key
   */
  const loadSaveVerify = async () => {
    try {
      const response = await saveVerify();
      if (response.code === 0) {
        setSaveVerifyDataState(response.data);
      }
    } catch (error) {}
  };

  const columns: ProColumns<AssessWeekCollectAppRecordData.RecordPage>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          统计范围
        </span>
      ),
      dataIndex: 'dataRangeDates',
      align: 'center',
      width: '200px',
      readonly: true,
      editable: false,
      render: (text, record, _, action) => {
        return (
          <>
            <Tag color={record.rangeState == 1 ? 'green' : 'red'}>
              {record.rangeState == 1 ? '进行中' : '已结束'}
            </Tag>
            {record.rangeStartDate} - {record.rangeEndDate}
          </>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          客户端
        </span>
      ),
      dataIndex: 'appName',
      align: 'center',
      ellipsis: true,
      width: '23%',
      render: (dom, entity, index, action) => {
        return (
          <span
            style={{
              color: entity?.totalDownloads == undefined ? '#ff4d4f' : '',
            }}
          >
            {entity.appName}
          </span>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          下载总数（单位：万）
        </span>
      ),
      dataIndex: 'totalDownloads',
      align: 'center',
      width: '85px',
      render: (dom, entity, index, action) => {
        return (
          <span
            style={{
              color: entity?.totalDownloads == undefined ? '#ff4d4f' : '',
            }}
          >
            {entity.totalDownloads}
          </span>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          发稿总数
        </span>
      ),
      dataIndex: 'totalCount',
      align: 'center',
      // sorter: true,
      // readonly: true,
      width: '85px',
      valueType: 'digit',
      fieldProps: {
        min: 0,
        max: 9999999,
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          万
        </span>
      ),
      dataIndex: 'count10000',
      align: 'center',
      // sorter: true,
      width: '85px',
      valueType: 'digit',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          十万
        </span>
      ),
      dataIndex: 'count100000',
      align: 'center',
      // sorter: true,
      width: '85px',
      valueType: 'digit',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          百万
        </span>
      ),
      dataIndex: 'count1000000',
      align: 'center',
      // sorter: true,
      width: '85px',
      valueType: 'digit',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          千万
        </span>
      ),
      dataIndex: 'count10000000',
      align: 'center',
      // sorter: true,
      width: '85px',
      valueType: 'digit',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          亿
        </span>
      ),
      dataIndex: 'count100000000',
      align: 'center',
      // sorter: true,
      width: '85px',
      valueType: 'digit',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 80,
      render: (text, record, _, action) => [
        <a
          hidden={record.isEdit == 0}
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  return (
    <EditableProTable<AssessWeekCollectAppRecordData.RecordPage>
      columns={columns}
      actionRef={actionRef}
      rowKey="id"
      request={async (params = {}, sorter) => {
        loadSaveVerify();
        const response = await pageRecord({
          ...params,
        });
        return {
          data: response.data?.data,
          success: true,
          total: response.data?.total,
        };
      }}
      dateFormatter="id"
      defaultSize={'small'}
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        defaultPageSize: 50,
      }}
      search={false}
      options={{
        density: false,
        setting: false,
      }}
      ghost
      scroll={{
        x: '1100px',
      }}
      headerTitle={
        <Alert
          message="客户端数据"
          type="info"
          showIcon
          style={{
            fontSize: 12,
          }}
        />
      }
      recordCreatorProps={false}
      editable={{
        actionRender: (row, config, defaultDom) => {
          return [defaultDom.save, defaultDom.cancel];
        },
        onSave: async (rowKey, data, row) => {
          const response = await updateRecord({
            id: data.id,
            totalDownloads: data.totalDownloads,
            totalCount: data.totalCount,
            count10000: data.count10000,
            count100000: data.count100000,
            count1000000: data.count1000000,
            count10000000: data.count10000000,
            count100000000: data.count100000000,
          });

          if (response.code == 0) {
            message.success('保存成功');
            actionRef.current?.reloadAndRest();
          } else {
            actionRef.current?.reloadAndRest();
          }
        },
      }}
      toolBarRender={() => [
        <Alert message="每周一17点关闭填报入口" type="error" showIcon />,
        access.传播质效x配置x运营员 && saveVerifyData && saveVerifyData?.isSaveVerify == 1 && (
          <AddRecord
            onRefurbish={function (): void {
              message.success('保存成功');
              actionRef.current?.reloadAndRest();
            }}
          />
        ),
      ]}
    />
  );
};
export default TabAppRecord;
